package com.reebake.ideal.jdbc;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import org.flywaydb.core.Flyway;

import javax.sql.DataSource;
import java.util.List;

/**
 * flyway工具类
 */
public class FlywayUtil {

    /**
     * 迁移数据库
     * @param dataSource 数据源
     * @param schema schema
     * @return flyway
     */
   public static Flyway migrate(DataSource dataSource, String schema) {
        List<String> locations = CollUtil.newArrayList("classpath:db/" + schema + "/migration/{vendor}");
        String table = "flyway_schema_history_" + schema;
        return FlywayUtil.migrate(dataSource, locations, table);
    }

    /**
     * 迁移数据库
     * @param dataSource 数据源
     * @param locations sql文件路径
     * @param table 历史记录表面
     * @return flyway
     */
    public static Flyway  migrate(DataSource dataSource, List<String> locations, String table) {
        JdbcLocationResolver locationResolver = new JdbcLocationResolver(dataSource);
        List<String> resolvedLocations = locationResolver.resolveLocations(locations);
        Flyway flyway = Flyway.configure()
                .dataSource(dataSource)
                .locations(ArrayUtil.toArray(resolvedLocations, String.class))
                .table(table)
                .cleanDisabled(true)
                .baselineOnMigrate(true)
                .load();
        flyway.migrate();
        return flyway;
    }

}
